package v1

import (
	"app/api/v1/response"
	"app/internal/app/model"
	"app/internal/pkg/ecode"
	"database/sql"

	"github.com/gin-gonic/gin"
)

type registerRequest struct {
	Account   uint   `form:"account" json:"account" binding:"required"`
	Password  string `form:"password" json:"password" binding:"required"`
	Name      string `form:"name" json:"name" binding:"required"`
	Nickname  string `form:"nickname" json:"nickname"`
	Telephone string `form:"telephone" json:"telephone"`
}

func Register(ctx *gin.Context) {
	var request *registerRequest
	err := ctx.ShouldBind(&request)
	if err != nil {
		response.Fail(ctx, ecode.ERROR_FORMAT)
		ctx.Abort()
		return
	}
	// user code validation
	if request.Account < 10000000 || request.Account > 99999999 {
		response.Fail(ctx, ecode.ERROR_USER_INVALID)
		ctx.Abort()
		return
	}
	_, err = model.CreateUser(&model.User{
		Account:   request.Account,
		Name:      request.Name,
		Nickname:  sql.NullString{String: request.Nickname},
		Telephone: sql.NullString{String: request.Telephone},
		Password:  request.Password,
	})

	if err != nil {
		response.Fail(ctx, err)
		return
	}

	response.Success(ctx, "", nil)
}
